<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row>
              <el-col :span="6">
                <el-form-item label="名称" prop="lawFirmName">
                  <el-input v-model="queryParams.lawFirmName" placeholder="请输入名称" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系手机" prop="contactPhone">
                  <el-input v-model="queryParams.contactPhone" placeholder="请输入联系手机" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="类型" prop="lawFirmType">
                  <el-select v-model="queryParams.lawFirmType" placeholder="请选择类型" clearable>
                    <el-option :key="1" label="个人" value="1"/>
                    <el-option :key="2" label="律所" value="2"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="首页选项" prop="curated">
                  <el-select v-model="queryParams.curated" placeholder="请选择首页选项" clearable>
                    <el-option :key="1" label="首页推荐" value="1"/>
                    <el-option :key="0" label="未推荐" value="0"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="区域" prop="districtId">
                  <el-select v-model="queryParams.districtId" placeholder="请选择区域" clearable>
                    <el-option v-for="region in regionList" :key="region.id" :label="region.regionName"
                               :value="region.id"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间" style="width: 308px">
                  <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lawfirm:info:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                       v-hasPermi="['lawfirm:info:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['lawfirm:info:remove']">删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="lawFirmList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="律所ID" align="center" prop="lawFirmId" v-if="false"/>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === '0'">启用</el-tag>
            <el-tag type="info" v-else>禁用</el-tag>
          </template>
        </el-table-column>
<!--        <el-table-column label="封面图片" align="center" prop="lawFirmLogo">-->
<!--          <template #default="scope">-->
<!--            <el-avatar shape="circle" :size="59" :src="scope.row.lawFirmLogo"/>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="名称" align="center" prop="lawFirmName">
          <template #default="scope">
            <el-tag v-if="scope.row.curated === '1'" type="warning">首页推荐</el-tag>
            {{ scope.row.lawFirmName }}
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="lawFirmType">
          <template #default="scope">
            <el-text v-if="scope.row.lawFirmType === '1'">个人</el-text>
            <el-text v-else>律所</el-text>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" prop="lawFirmTag">
          <template #default="scope">
          <el-tooltip :content="scope.row.lawFirmTag" placement="top">
            <el-text truncated>{{ scope.row.lawFirmTag }}</el-text>
          </el-tooltip>
          </template>
        </el-table-column>
        <!--        <el-table-column label="管理员" align="center" prop="nickname" />-->
        <el-table-column label="联系手机" align="center" prop="contactPhone"/>
        <el-table-column label="登录账号" align="center" prop="account">
          <template #default="scope">
            {{ scope.row.account }}
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" prop="lawFirmAddress">
          <template #default="scope">
            <el-text line-clamp="2">{{ scope.row.lawFirmAddress }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"/>
        <el-table-column label="评价" align="center" class-name="small-padding fixed-width" width="50">
          <template #default="scope">
            <el-tooltip content="点击查看所有评价信息" placement="top">
              <router-link :to="'/lawfirm/info-comment/index/' + scope.row.lawFirmId" class="link-type">
                <el-icon>
                  <CopyDocument/>
                </el-icon>
              </router-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="荣誉" align="center" class-name="small-padding fixed-width" width="50">
          <template #default="scope">
            <el-tooltip content="点击查看所有荣誉信息" placement="top">
              <router-link :to="'/lawfirm/award/index/' + scope.row.lawFirmId" class="link-type">
                <el-icon>
                  <Medal/>
                </el-icon>
              </router-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="案例" align="center" class-name="small-padding fixed-width" width="50">
          <template #default="scope">
            <el-tooltip content="点击查看所有案例信息" placement="top">
              <router-link :to="'/lawfirm/case/index/' + scope.row.lawFirmId" class="link-type">
                <el-icon>
                  <Folder/>
                </el-icon>
              </router-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="律师" align="center" class-name="small-padding fixed-width" width="50">
          <template #default="scope">
            <el-tooltip content="点击查看所有律师信息" placement="top">
              <router-link :to="'/lawfirm/lawyer/index/' + scope.row.lawFirmId" class="link-type">
                <el-icon>
                  <User/>
                </el-icon>
              </router-link>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding" width="180">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="Warning" @click="handleInfo(scope.row)"
                         v-hasPermi="['lawfirm:info:query']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['lawfirm:info:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="重置密码" placement="top">
              <el-button link type="warning" icon="Key" @click="handleResetPwd(scope.row)"
                         v-hasPermi="['wxuser:wxuser:resetpwd']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0'" content="冻结用户,禁止登录" placement="top">
              <el-button link type="primary" icon="Lock" @click="handleInactive(scope.row)"
                         v-hasPermi="['lawfirm:info:inactive']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '1'" content="启用用户，允许登录" placement="top">
              <el-button link type="primary" icon="Unlock" @click="handleActive(scope.row)"
                         v-hasPermi="['lawfirm:info:active']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['lawfirm:info:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改律所信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="836px" append-to-body>
      <el-form ref="lawFirmFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="封面图片" prop="lawFirmLogo">
          <imageUpload single :limit="1" v-model="form.lawFirmLogo"/>
        </el-form-item>
        <el-form-item label="名称" prop="lawFirmName">
          <el-input v-model="form.lawFirmName" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="类型" prop="lawFirmType">
          <el-radio-group v-model="form.lawFirmType">
            <el-radio value="2">律所</el-radio>
            <el-radio value="1">个人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.lawFirmType === '1'" label="律所名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入律所名称"/>
        </el-form-item>
        <el-form-item label="地区" prop="cityId">
<!--          <el-select v-model="form.districtId" placeholder="请选择区域" clearable>-->
<!--            <el-option v-for="region in regionList" :key="region.id" :label="region.regionName" :value="region.id"/>-->
<!--          </el-select>-->
          <el-tree-select
            v-model="form.cityId"
            :data="regionList"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="选择地区"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="标签" prop="lawFirmTag">
          <el-input v-model="form.lawFirmTag" placeholder="请输入标签" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item v-if="form.lawFirmId == undefined" label="管理员姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item v-if="form.lawFirmId == undefined" label="管理员手机" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系手机"/>
        </el-form-item>
        <el-form-item v-if="form.lawFirmId == undefined" label="登录账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入登录账号"/>
        </el-form-item>
        <el-form-item v-if="form.lawFirmId == undefined" label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码"/>
        </el-form-item>
        <el-form-item label="首页选项" prop="curated">
          <el-radio-group v-model="form.curated">
            <el-radio value="0">不推荐</el-radio>
            <el-radio value="1">首页推荐</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="综合评分" prop="rating">-->
        <!--          <el-input-number v-model="form.rating" :min="0" :step-strictly="true" controls-position="right"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="粉丝数量" prop="followers">-->
        <!--          <el-input-number v-model="form.followers" :min="0" :step-strictly="true" controls-position="right"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="执业认证" prop="certification">
          <el-radio-group v-model="form.certification">
            <el-radio value="1">已认证</el-radio>
            <el-radio value="0">未认证</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执业开始时间" prop="yearServiceTime" v-if="form.lawFirmType === '1'">
          <el-date-picker clearable
                          v-model="form.yearServiceTime"
                          type="datet"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择执业开始时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--详情-->
    <LawFirmInfoDialog ref="lawFirmInfoDialogRef"/>
  </div>
</template>

<script setup name="LawFirmInfo" lang="ts">
import {
  listLawFirm,
  getLawFirm,
  delLawFirm,
  addLawFirm,
  updateLawFirm,
  activeLawFirm,
  inactiveLawFirm
} from '@/api/lawfirm/lawfirm';
import {LawFirmVo, LawFirmQuery, LawFirmForm} from '@/api/lawfirm/lawfirm/types';
import {SysRegionVo} from '@/api/region/types';
import {treeSysRegion } from '@/api/region';
import {resetPwd} from '@/api/wxuser';
import {to} from 'await-to-js';

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const LawFirmInfoDialog = defineAsyncComponent(() => import('@/views/lawfirm/info/infoDialog.vue'));

const lawFirmList = ref<LawFirmVo[]>([]);
const regionList = ref<SysRegionVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const lawFirmFormRef = ref<ElFormInstance>();
const lawFirmInfoDialogRef = ref();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const lawFirmLabel = ref('律所');
const initFormData: LawFirmForm = {
  lawFirmId: undefined,
  lawFirmName: undefined,
  lawFirmLogo: undefined,
  lawFirmType: '2',
  lawFirmDesc: undefined,
  lawFirmAddress: undefined,
  companyName: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  rating: 0,
  curated: '0',
  followers: 0,
  certification: '1',
  yearServiceTime: undefined,
  contactPhone: undefined,
  contactName: undefined,
  account: undefined,
  password: undefined,
  districtId: undefined,
  lawFirmTag: undefined
};


const data = reactive<PageData<LawFirmForm, LawFirmQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    lawFirmName: undefined,
    lawFirmType: undefined,
    province: undefined,
    city: undefined,
    districtId: undefined,
    curated: undefined,
    contactPhone: undefined,
    params: {}
  },
  rules: {
    lawFirmName: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    lawFirmType: [
      {required: true, message: "类型不能为空", trigger: "change"}
    ],
    contactName: [
      {required: true, message: "联系人不能为空", trigger: "blur"}
    ],
    account: [
      {required: true, message: "登录账号不能为空", trigger: "blur"},
      {
        min: 2,
        max: 20,
        message: '用户名称长度必须介于 2 和 20 之间',
        trigger: 'blur'
      }
    ],
    password: [
      {required: true, message: "登录密码不能为空", trigger: "blur"},
      {
        min: 5,
        max: 20,
        message: '用户密码长度必须介于 5 和 20 之间',
        trigger: 'blur'
      },
      {pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur'}
    ],
    curated: [
      {required: true, message: "首页选项不能为空", trigger: "blur"}
    ],
    certification: [
      {required: true, message: "执业认证不能为空", trigger: "blur"}
    ],
    districtId: [
      {required: true, message: "地区不能为空", trigger: "blur"}
    ],
    yearServiceTime: [
      {required: true, message: "执业开始时间不能为空", trigger: "blur"}
    ],
    contactPhone: [
      {required: true, message: "联系手机不能为空", trigger: "blur"},
      {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur'}
    ],
    lawFirmTag:[
      {
        max: 14,
        message: '标签字符数不能超过14个字',
        trigger: 'blur'
      }
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

watchEffect(() =>{
    if(form.value.lawFirmType === '1'){
      lawFirmLabel.value = '律师';
    }else{
      lawFirmLabel.value = '律所';
    }
});

/** 查询律所信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLawFirm(proxy?.addDateRange(queryParams.value, dateRange.value));
  lawFirmList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const getRegionList = async () => {
  const res = await treeSysRegion();
  regionList.value = res.data;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  lawFirmFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: LawFirmVo[]) => {
  ids.value = selection.map(item => item.lawFirmId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: LawFirmVo) => {
  reset();
  const _lawFirmId = row?.lawFirmId || ids.value[0];
  const res = await getLawFirm(_lawFirmId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改信息';
};

const handleInfo = async (row?: LawFirmVo) => {
  lawFirmInfoDialogRef.value.openDialog(row);
};

/** 提交按钮 */
const submitForm = () => {
  lawFirmFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.lawFirmId) {
        await updateLawFirm(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addLawFirm(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: LawFirmVo) => {
  const _lawFirmIds = row?.lawFirmId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delLawFirm(_lawFirmIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 重置密码按钮操作 */
const handleResetPwd = async (row: LawFirmVo) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入"' + row.lawFirmName + '"的新密码', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      inputValidator: (value) => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return '不能包含非法字符：< > " \' \\\ |';
        }
      }
    })
  );
  if (!err && res) {
    await resetPwd(row.adminUserId, res.value);
    proxy?.$modal.msgSuccess('修改成功，新密码是：' + res.value);
  }
};

const handleActive = async (row?: LawFirmVo) => {
  const _lawFirmId = row?.lawFirmId;
  const text = `是否确认启用${row.lawFirmName}？`;
  await proxy?.$modal.confirm(text).finally(() => loading.value = false);
  await activeLawFirm(_lawFirmId);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

const handleInactive = async (row?: LawFirmVo) => {
  const _lawFirmId = row?.lawFirmId;
  const text = `是否确认冻结${row.lawFirmName}？`;
  await proxy?.$modal.confirm(text).finally(() => loading.value = false);
  await inactiveLawFirm(_lawFirmId);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

onMounted(() => {
  getList();
  getRegionList();
});
</script>
